package com.ykun.mq.work;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

/**
 * @author YKun
 * @date 2017年4月24日 下午10:37:20
 * @describe
 */
public class NewTask {

	private static final String TASK_QUEUE_NAME = "task_queue";

	public static void main(String[] args) throws IOException, TimeoutException {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("127.0.0.1");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		// param1: 队列名 param2: 是否持久化
		channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

		String message = getMessage(args);
		
		// PERSISTENT_TEXT_PLAIN: Content-type "text/plain", deliveryMode 2 (persistent), priority zero
		channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes("UTF-8"));
		System.out.println(" [x] Sent '" + message + "'");
		

	    channel.close();
	    connection.close();
	}

	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World.............";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0)
			return "";
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}

}
